package com.foreverwin.mes.mq.aspect;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.common.model.EapLog;
import com.foreverwin.mes.core.utils.IPUtil;
import com.foreverwin.mes.core.utils.ObjectMapperUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * @author Ervin Chen
 * @date 2020/3/20 21:19
 */

@Aspect
@Component
public class EapLogAspect {

    private Logger logger = LoggerFactory.getLogger(EapLogAspect.class);

    @Autowired
    JmsMessagingTemplate jmsTemplate;

    @Value("${spring.activemq.brokerUrl}")
    String brokerURL;

    @Pointcut("@annotation(org.springframework.jms.annotation.JmsListener) && !execution(* com.foreverwin.mes.mq.listener.EapLogListener.*(..))")
    public void messageLog() {
    }

    @AfterReturning(pointcut = "messageLog()")
    public void doAfterReturning(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    @AfterThrowing(pointcut = "messageLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    public void handleLog(JoinPoint joinPoint, Exception e) {
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        JmsListener jmsListener = methodSignature.getMethod().getAnnotation(JmsListener.class);

        String queueName = jmsListener.destination();
        String messageBody = (String) args[0];

        JSONObject map = JSONObject.parseObject(messageBody);
        String site = map.getString("SITE");
        String ip = IPUtil.getIp();
        String result = null;
        String errorMsg = null;
        if (e == null) {
            result = "Y";
        } else {
            result = "N";
            errorMsg = e.getMessage();
        }

        EapLog eapLog = new EapLog();
        eapLog.setHandle(UUID.randomUUID().toString());
        eapLog.setSite(site);
        eapLog.setBroker(brokerURL);
        eapLog.setQueue(queueName);
        eapLog.setMessageBody(messageBody != null && messageBody.length() > 2000 ? messageBody.substring(0, 2000) : messageBody);
        eapLog.setResult(result);
        eapLog.setError(errorMsg != null && errorMsg.length() > 2000 ? errorMsg.substring(0, 2000) : errorMsg);
        eapLog.setServerId(ip);
        eapLog.setMessageType("out");
        eapLog.setCreatedDateTime(new Date());

        jmsTemplate.convertAndSend("MES_EAP_LOG", ObjectMapperUtil.writeValueAsString(eapLog));
    }
}
